package com.example.a001.part1802;

import android.os.Bundle;
import android.widget.DatePicker;
import android.widget.TextView;
import android.widget.TimePicker;
import androidx.appcompat.app.AppCompatActivity;

import com.example.a001.R;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

    private DatePicker datePicker;
    private TimePicker timePicker;
    private TextView selectedDateTimeText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main5);

        datePicker = findViewById(R.id.datePicker);
        timePicker = findViewById(R.id.timePicker);
        selectedDateTimeText = findViewById(R.id.selectedDateTimeText);

        Calendar cal = Calendar.getInstance();
        int year = cal.get(Calendar.YEAR);
        int month = cal.get(Calendar.MONTH);
        int day = cal.get(Calendar.DAY_OF_MONTH);

        datePicker.init(year, month, day, new DatePicker.OnDateChangedListener() {
            @Override
            public void onDateChanged(DatePicker view, int selectedYear, int selectedMonth, int selectedDay) {
                updateSelectedDateTime(selectedYear, selectedMonth, selectedDay, timePicker.getHour(), timePicker.getMinute());
            }
        });

        timePicker.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
            @Override
            public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
                updateSelectedDateTime(datePicker.getYear(), datePicker.getMonth(), datePicker.getDayOfMonth(), hourOfDay, minute);
            }
        });

        // 初始化显示当前日期和时间
        updateSelectedDateTime(year, month, day, cal.get(Calendar.HOUR_OF_DAY), cal.get(Calendar.MINUTE));
    }

    private void updateSelectedDateTime(int year, int month, int day, int hourOfDay, int minute) {
        String selectedDate = String.format("%d-%02d-%02d %02d:%02d", year, month + 1, day, hourOfDay, minute);
        selectedDateTimeText.setText("选择的日期和时间是: " + selectedDate);
    }
}
